<?php
namespace app\api\controller;

use EasyWeChat\MiniApp\Application;
use app\api\logic\WechatUserLogic;
use plugin\saiadmin\app\logic\system\SystemConfigLogic;
use plugin\saiadmin\basic\OpenController;
use plugin\saiadmin\utils\Arr;
use support\Request;
use app\api\annotation\LoginRequired;
use app\api\basic\BaseController;
use app\api\model\WechatUser;
use support\think\Db;

 #[LoginRequired(required: false)]
class WechatController extends BaseController
{
   protected $app;
   protected $appId;
   protected $secret;
 
    public function __construct()
    {
        parent::__construct();
        $logic = new SystemConfigLogic();
        $wechatConfig = $logic->getGroup('wechat');
        $this->appId=Arr::getConfigValue($wechatConfig,'minAppId');
        $this->secret=Arr::getConfigValue($wechatConfig,'minAppSecret');
        $config = [
            'app_id' =>$this->appId,
            'secret' =>$this->secret,
            'token' => '',
            'aes_key' => '',
            'http' => [
                'throw'  => true, // 状态码非 200、300 时是否抛出异常，默认为开启
                'timeout' => 5.0,
               
        
                'retry' => true, // 使用默认重试配置
            ],
            "use_stable_access_token"=>true,
            "use_stable_redis"=>true,
        ];
      
        $this->app = new Application($config);
    }
   
    //获取登录信息
    public function jscode2session(Request $request){
        $param = $request->more([
            ['js_code',''],
            ['lang_code','zh']
        ]);
        
        try{
        $res=$this->app->getClient()->get('https://api.weixin.qq.com/sns/jscode2session',[
            'appid' =>$this->appId,
            'secret' =>$this->secret,
            'js_code'=>$param['js_code'],
            'grant_type'=>'authorization_code',
        ]);
       
      
        $row=$res->getContent();
     
        $row=json_decode($row,true);
        //   print_r($row);exit();
        if(isset($row['errcode'])){
             return $this->fail($row['errmsg']);
        }
        //todo登录
        $userLogic=new WechatUserLogic();
        $data['lang_code']=$param['lang_code'];
        $data['openid']=$row['openid'];
        $userinfo=$userLogic->loginByWechat($data);
        if($userinfo['user']){
              return $this->success($userinfo,'登录成功'); 
        }
       return json(['code' => 402, 'message' => '请注册', 'data' => $userinfo]);
             
      }catch(\Exception $e){
          error_log('Error processing js_code: '. $param['js_code']. ', Error: '. $e->getMessage());
        return $this->fail($e->getMessage());
      }
    }
    public function getPhoneNumber(Request $request){
        $param = $request->more([
            ['code',''],
        ]);
      if($param['code']=='') return $this->fail('code不能为空');
      try{
        $AccessToken=$this->app->getAccessToken()->getToken();
       
     
        $res = $this->app->getClient()->post(
                'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $AccessToken,
                [
                    'headers' => [
                        'Content-Type' => 'application/json'
                    ],
                    'json' => [
                        'code' => $param['code']
                    ]
                ]
            );
        
      
        $row=$res->getContent();
      
        $row=json_decode($row,true);
        if(isset($row['errcode'])){
           if($row['errcode']!=0)  return $this->fail($row['errmsg']);
        }
         $phone=$row['phone_info']['purePhoneNumber'];
             return $this->success(['phone'=>$phone],'手机号获取成功');         
      }catch(\Exception $e){
          error_log('Error processing code: '. $param['code']. ', Error: '. $e->getMessage());
        return $this->fail($e->getMessage());
      }
    }
    //获取手机号
    public function regesterUser(Request $request){

      
        $param = $request->more([
            ['phone',''],
            ['openid',''],
            ['nickname',''],
            ['avatar',''],
            ['lang_code','zh']
        ]);
        if($param['phone']=='') return $this->fail('phone不能为空');
        if($param['openid']=='') return $this->fail('openid不能为空');
        if($param['nickname']=='') return $this->fail('nickname不能为空');
        if($param['avatar']=='') return $this->fail('avatar不能为空');
          
        $userLogic=new WechatUserLogic();
        //todo 业务逻辑处理
        $data['lang_code']=$param['lang_code'];
        $data['openid']=$param['openid'];
        $data['avatar']=$param['avatar'];
        $data['nickname']=$param['nickname'];
        $data['phone']=$param['phone'];
        $userinfo=$userLogic->regesterUser($data);
        if(!$userinfo) $this->fail('注册失败');
      
        $userinfo['policy_num']=0;
        $userinfo['supply_demand_num']=0;
        $userinfo['talents_num']=0;
        $userinfo['space_num']=0;
        //todo返回token
        return $this->success($userinfo,'注册成功');         
    }
   
     public function jscode2sessiontest(Request $request){
       
        $param = $request->more([
            ['js_code',''],
            ['lang_code','zh']
        ]);
        // $res=$this->app->getClient()->get('https://api.weixin.qq.com/sns/jscode2session',[
        //     'js_code'=>$param['js_code'],
        //     'grant_type'=>'authorization_code',
        // ]);
        // $row=$res->getBody()->getContents();
        // $row=json_decode($row,true);
        //todo登录
        $userLogic=new WechatUserLogic();
        $data['lang_code']=$param['lang_code'];
        $data['openid']=$row['openid']??'oAAoB7rvMPr3DRLzJgif4p1GabHM';
        $userinfo=$userLogic->loginByWechat($data);
        
     
        //todo返回token
        return $this->success($userinfo,'登录成功');         
       
    }
     public function jscode2sessionDel(Request $request){
       
        $param = $request->more([
            ['openid','']
        ]);
       
        if($param['openid']=='') return $this->fail('openid不能为空');
        // $res=$this->app->getClient()->get('https://api.weixin.qq.com/sns/jscode2session',[
        //     'js_code'=>$param['js_code'],
        //     'grant_type'=>'authorization_code',
        // ]);
        // $row=$res->getBody()->getContents();
        // $row=json_decode($row,true);
        //todo登录
        // $userLogic=new WechatUserLogic();
        $res = Db::table('eb_wechat_user')->where('openid', $param['openid'])->delete();
        
        if(!$res) return $this->fail('删除失败');
        
        
     
        //todo返回token
        return $this->success('删除成功');         

       
    }
}